package com.awei.study.dataStructure.queue;

import com.awei.study.dataStructure.queue.abs.Queue;

import java.util.Iterator;

/**
 * @Author liweilong
 * @Date 2023/5/23 14:41
 */
public class ArrayQueue2<E> implements Queue<E>, Iterable<E> {

    private E[] array;
    public int head = 0;
    public int tail = 0;
    private int capacity = Integer.MAX_VALUE;

    @SuppressWarnings("all")
    public ArrayQueue2(int capacity) {
        array = (E[]) new Object[capacity];
        this.capacity = capacity;
    }

    @Override
    public boolean offer(E value) {
        if (isFull()) return false;
        array[(int) (Integer.toUnsignedLong(tail) % array.length)] = value;
        tail++;
        System.out.println(tail);
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()) return null;
        E value = array[(int) (Integer.toUnsignedLong(head) % array.length)];
        head++;
        return value;
    }

    @Override
    public E peek() {
        if (isEmpty()) return null;
        E value = array[(int) (Integer.toUnsignedLong(head) % array.length)];
        return value;
    }

    @Override
    public boolean isFull() {
//        return (tail + 1 ) % array.length == head % array.length ;
        return tail - head == array.length;
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = head;

            @Override
            public boolean hasNext() {
                return p != tail;
            }

            @Override
            public E next() {
                E value = array[(int) (Integer.toUnsignedLong(p) % array.length)];
                p++;
                return value;
            }
        };
    }
}
